package com.tsy.common.utils.converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PointCloudUtil {

    // 定义 Converter 工具的路径，根据不同系统进行设置
//    private static final String CONVERTER_WINDOWS = "PotreeConverter\\build\\PotreeConverter.exe";
    private static final String CONVERTER_WINDOWS = "C:\\Users\\Administrator\\Desktop\\PotreeConverter\\build\\PotreeConverter.exe";
    private static final String CONVERTER_LINUX = "/app/PotreeConverter/build/PotreeConverter";
    // 根据当前系统选择合适的工具路径
    private static final String CONVERTER_TOOL = System.getProperty("os.name").startsWith("Windows") ? CONVERTER_WINDOWS : CONVERTER_LINUX;

    // 添加带进度回调的方法
    public static boolean pintCloudConverter(String srcPath, String destPath, Consumer<Integer> progressCallback) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果图片保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(CONVERTER_TOOL);
        cmd.append(" ");
        cmd.append("-i ");
        cmd.append(srcPath);
        cmd.append(" -o ");
        cmd.append(destPath);
        System.out.println("执行命令: " + cmd);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            ProgressThread error = new ProgressThread(proc.getErrorStream(), progressCallback, "错误输出");
            ProgressThread output = new ProgressThread(proc.getInputStream(), progressCallback, "标准输出");
            error.start();
            output.start();
            proc.waitFor();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    // 保持原有方法向后兼容
    public static boolean pintCloudConverter(String srcPath, String destPath) {
        return pintCloudConverter(srcPath, destPath, null);
    }

    // 改进的进度处理线程 - 使用BufferedReader实时读取每一行，而不是读取固定大小的块
    public static class ProgressThread extends Thread {
        private final InputStream is;
        private final Consumer<Integer> progressCallback;
        private final String streamType;

        public ProgressThread(InputStream is, Consumer<Integer> progressCallback, String streamType) {
            this.is = is;
            this.progressCallback = progressCallback;
            this.streamType = streamType;
        }

        @Override
        public void run() {
            try {
                // 使用BufferedReader按行读取而不是使用固定大小的缓冲区
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    // 立即输出每一行，不累积
                    System.out.println(streamType + ": " + line);
                    
                    // 如果有进度回调，尝试解析进度信息
                    if (progressCallback != null) {
                        // 使用正则表达式匹配可能的进度格式
                        String content = line.toLowerCase();
                        try {
                            if (content.contains("progress") || content.contains("%") ||
                                content.contains("进度")) {
                                // 提取数字
                                // 定义正则表达式
                                String regex = "(\\d+)%";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(content);
                                if (matcher.find()) {
                                    int progress = Integer.parseInt(matcher.group(1));
                                    // 确保进度在有效范围内
                                    if (progress >= 0 && progress <= 100) {
                                        progressCallback.accept(progress);
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            // 解析失败时静默处理，继续等待下一次输出
                            System.out.println("进度解析失败: " + line);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("开始转换测试...");
        PointCloudUtil.pintCloudConverter("C:\\Users\\Administrator\\Desktop\\test.las", "C:\\Users\\Administrator\\Desktop\\converter1\\test", progress -> {
            System.out.println("当前进度: " + progress + "%");
        });
        System.out.println("转换测试完成");
        // 获取当前工作目录
//        String workingDirectory = System.getProperty("user.dir");
//        System.out.println("当前工作目录是: " + workingDirectory);
    }

}

